package com.ybt.heartratem.common.app;

import android.os.Handler;
import android.os.Looper;

import com.ybt.heartratem.logic.data.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 应用实例整体控制器
 */
public class AppController {
    private static final String TAG = AppController.class.getCanonicalName();
    /**
     * Hanldr Looper
     */
    public static Handler mMainHandler = new Handler(Looper.getMainLooper());

    /**
     * 存储所有页面Handler键值对
     * key:getClass().getCanonicalName()
     * value:页面Handler
     * !注意页面销毁时remove掉!
     */
    private Map<String, Handler> handlerMap = new HashMap<String, Handler>();
    private static AppController instance;
    private List<OnRefreshListener> onRefreshListeners = new ArrayList<>();
    /**
     * Looper线程
     */
    private LooperThread looperThread;

    /**
     * 初始化项目用到的类
     */
    private AppController() {
        looperThread = new LooperThread();
        looperThread.setName("LooperThread");
        looperThread.start();
    }

    public static AppController getInstance() {
        synchronized (AppController.class) {
            if (null == instance) {
                instance = new AppController();
            }
        }
        return instance;
    }

    public Map<String, Handler> getHandlerMap() {
        return handlerMap;
    }

    /************Get方法******end******/
    /*** 单线程执行数据的刷新操作*/
    public class LooperThread extends Thread {
        /*** 线程内部handler*/
        public Handler handler;
        /*** 线程内部Looper*/
        public Looper looper;

        @Override
        public void run() {
            Looper.prepare();
            looper = Looper.myLooper();
            handler = new Handler() {
                public void handleMessage(android.os.Message msg) {
                }
            };
            Looper.loop();
        }
    }

    public void regOnRefreshListener(OnRefreshListener listener) {
        if (!onRefreshListeners.contains(listener)) {
            onRefreshListeners.add(listener);
        }
    }

    public void postOnRefreshListener(String weight) {
        mMainHandler.post(() -> {
            for (OnRefreshListener listener : onRefreshListeners) {
                listener.onRefresh(weight);
            }
        });
    }
}
